package com.ramos.kuaixiao.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.hzy.lib7z.Z7Extractor;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.MemoryCacheAware;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.BuildConfig;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.db.BrandInfoDB;
import com.ramos.kuaixiao.db.DBHelper;
import com.ramos.kuaixiao.db.OrderDB;
import com.ramos.kuaixiao.db.ShopsDB;
import com.ramos.kuaixiao.entity.SendOrderDetail;
import com.ramos.kuaixiao.network.DownloadClientPriceTask;
import com.ramos.kuaixiao.network.DownloadCustomerStoreTask;
import com.ramos.kuaixiao.network.DownloadCustomerTask;
import com.ramos.kuaixiao.network.DownloadEmpBrandTask;
import com.ramos.kuaixiao.network.DownloadEmpStorehouseTask;
import com.ramos.kuaixiao.network.DownloadKeyWordsTask;
import com.ramos.kuaixiao.network.DownloadPriceTask;
import com.ramos.kuaixiao.network.DownloadPriceTypeTask;
import com.ramos.kuaixiao.network.DownloadStoreNumTask;
import com.ramos.kuaixiao.network.DownloadUpdateFileTask;
import com.ramos.kuaixiao.network.UpdateBrandKeywordTask;
import com.ramos.kuaixiao.network.UpdateClientPriceTask;
import com.ramos.kuaixiao.network.UpdateCustomerStoreTask;
import com.ramos.kuaixiao.network.UpdateCustomerTask;
import com.ramos.kuaixiao.network.UpdateEmpBrandTask;
import com.ramos.kuaixiao.network.UpdateEmpStorehouseTask;
import com.ramos.kuaixiao.network.UpdateOrderTask;
import com.ramos.kuaixiao.network.UpdatePriceTypeTask;
import com.ramos.kuaixiao.network.UpdateProductPriceTask;
import com.ramos.kuaixiao.network.UpdateSaleCustomerStoreTask;
import com.ramos.kuaixiao.network.UpdateSaleCustomerTask;
import com.ramos.kuaixiao.network.UpdateShopsTask;
import com.ramos.kuaixiao.network.UpdateStoreHouseTask;
import com.ramos.kuaixiao.network.UpdateStoreNumTask;
import com.ramos.kuaixiao.utils.AppManager;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.DownloadImageTask;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.StartLocation;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executors;


public class MainActivity extends BaseActivity implements View.OnClickListener {
    private final static String TAG = "MainActivity";
    // 定义FragmentManager对象管理器
    private FragmentManager fragmentManager;
    private RelativeLayout re_home_shop;
    private RelativeLayout re_home_order;
    private RelativeLayout re_home_task;
    private RelativeLayout re_home_my;
    private ShopFragment mShopFragment;
    private OrderFragment mOrderFragment;
    private MallFragment mMallFragment;
    private UserFragment mUserFragment;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_SUCCESS1 = 200;
    public final static int UPLOAD_SUCCESS2 = 300;
    public final static int UPLOAD_FAIL = 101;
    public final static int UPLOAD_FAIL1 = 201;
    public final static int UPLOAD_FAIL2 = 301;
    private TextView tv_home_shop;
    private TextView tv_home_order;
    private TextView tv_home_task;
    private TextView tv_home_my;
    private ImageView ib_home_shop;
    private ImageView ib_home_order;
    private ImageView ib_home_task;
    private ImageView ib_home_my;
    private long exitTime = 0;
    StartLocation startLocation;
    private LocationManager lm;//【位置管理】
    public static DisplayImageOptions mNormalImageOptions;
    public static final String SDCARD_PATH = Environment.getExternalStorageDirectory().toString();
    public static final String IMAGES_FOLDER = SDCARD_PATH + File.separator + "demo" + File.separator + "images" + File.separator;
    private int mCurrentPage = 1;
    public static Context mContext;
    private long mExitTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startLocation = new StartLocation(this);
        startLocation.startLocation();
        mContext = this;
        setContentView(R.layout.activity_main);
        initImageLoader(this);
        Log.d("onUpgrade", "MainActivity,App.isOldVersion:"+ App.isOldVersion);
        if(App.isOldVersion){
            startActivity(new Intent(MainActivity.this, LoadingActivity.class));
        }
        initView();
    }

    private void initImageLoader(Context context) {
        int memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 5);
        MemoryCacheAware<String, Bitmap> memoryCache;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            memoryCache = new LruMemoryCache(memoryCacheSize);
        } else {
            memoryCache = new LRULimitedMemoryCache(memoryCacheSize);
        }

        mNormalImageOptions = new DisplayImageOptions.Builder().bitmapConfig(Bitmap.Config.RGB_565).cacheInMemory(true).cacheOnDisc(true)
                .resetViewBeforeLoading(true).build();

        // This
        // This configuration tuning is custom. You can tune every option, you
        // may tune some of them,
        // or you can create default configuration by
        // ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).defaultDisplayImageOptions(mNormalImageOptions)
                .denyCacheImageMultipleSizesInMemory().discCache(new UnlimitedDiscCache(new File(IMAGES_FOLDER)))
                // .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .memoryCache(memoryCache)
                // .memoryCacheSize(memoryCacheSize)
                .tasksProcessingOrder(QueueProcessingType.LIFO).threadPriority(Thread.NORM_PRIORITY - 2).threadPoolSize(3).build();

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }


    private void initView() {
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        fragmentManager = getSupportFragmentManager();
        re_home_shop = findViewById(R.id.re_home_shop);
        re_home_order = findViewById(R.id.re_home_order);
        re_home_task = findViewById(R.id.re_home_task);
        re_home_my = findViewById(R.id.re_home_my);
        re_home_shop.setOnClickListener(this);
        re_home_order.setOnClickListener(this);
        re_home_task.setOnClickListener(this);
        re_home_my.setOnClickListener(this);

        ib_home_shop = (findViewById(R.id.ib_home_shop));
        ib_home_order = (findViewById(R.id.ib_home_order));
        ib_home_task = (findViewById(R.id.ib_home_task));
        ib_home_my = (findViewById(R.id.ib_home_my));

        tv_home_shop = (findViewById(R.id.tv_home_shop));
        tv_home_order = (findViewById(R.id.tv_home_order));
        tv_home_task = (findViewById(R.id.tv_home_task));
        tv_home_my = (findViewById(R.id.tv_home_my));
        AppManager.getAppManager().addActivity(this);
        showShop();
        new DownloadImageTask().execute();
        /*App.ZipUrl = FileUtil.getDataPath(App.mContext) + "/dbinfo";
        File file = new File(FileUtil.getDataPath(App.mContext));
        if (!file.exists() || file.list().length == 0 || SharedPreference.getPreferInteger("isFirstLogin") == 0 || App.mUserChanged) {
            file.delete();
            *//*if (Z7Extractor.extractAsset(App.mContext.getAssets(), "dbinfo.7z", FileUtil.getDataPath(this), null)){
                Log.d(TAG, "extractAsset true" );
                getData();
                new BrandInfoDB().clearShopMall();
            }*//*
            getZipFile();
        } else {
            if(new CustomerDB().findAllCustomer().size() == 0 || new ShopsDB().findAllShops().size() == 0){
                getZipFile();
            } else {
                loadData(2);
            }
        }*/
        App.mProductInfos.clear();
        App.mProductInfos.addAll(new ShopsDB().findAllUseShops());

        App.mOrderList.clear();
        App.mOrderList.addAll(new OrderDB().findAllOrder());

        loadData(2);
    }

    private void loadData(int i) {
        /*if (i == 1) {
            //Utils.executeFixedRate(UpdateHouseTask.getInstance(), 1000 * 60 , 1000 * 30);
            Utils.executeFixedRate(new ApkUpdateTask(), 1000 * 60 * 2, 1000 * 60 * 2);
        } else {
            //Utils.executeFixedRate(UpdateHouseTask.getInstance(), 1000 * 30, 1000 * 30);
            Utils.executeFixedRate(new ApkUpdateTask(), 0, 1000 * 60 * 2);
        }*/
        Utils.executeFixedRate(new ApkUpdateTask(), 0, 1000 * 60 * 1);
    }

    private void getZipFile() {
        try {
            String url = NetUtils.GET_ZIP;
            CommUtil.d(mContext, TAG, "getZipFile " + url);
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            client.get(url, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String zipUrl = Utils.getZipFile(responseBody, FileUtil.getZipPath(App.mContext), BuildConfig.DOWNLOAD_NAME);
                        CommUtil.d(mContext, TAG, "getZipFile:onSuccess:" + zipUrl);
                        if (!StringUtil.isEmpty(zipUrl)) {
                            Log.d(TAG, "zipUrl:isNotEmpty" + zipUrl);
                            if (Z7Extractor.extractFile(zipUrl, FileUtil.getZipPath(mContext), null)) {
                                getData();
                                new BrandInfoDB().clearShopMall();
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getData() {
        try {
            File dirFile = new File(FileUtil.getDataPath(mContext));
            File[] files = dirFile.listFiles();
            if (files.length > 0) {
                for (File file : files) {
                    CommUtil.d(mContext, TAG, "file:" + file.getName() + " " + file.getAbsolutePath());
                    if (file.getName().equals("tbl_customer.csv")) {
                        DownloadCustomerTask product = new DownloadCustomerTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_customer_store.csv")) {
                        DownloadCustomerStoreTask product = new DownloadCustomerStoreTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_emp_brand.csv")) {
                        DownloadEmpBrandTask product = new DownloadEmpBrandTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_emp_storehouse.csv")) {
                        DownloadEmpStorehouseTask product = new DownloadEmpStorehouseTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_pricetype.csv")) {
                        DownloadPriceTypeTask product = new DownloadPriceTypeTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_productprice.csv")) {
                        DownloadPriceTask product3 = new DownloadPriceTask();
                        product3.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_so_org_customer_salesperson.csv")) {
                        DownloadClientPriceTask product10 = new DownloadClientPriceTask();
                        product10.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_stock.csv")) {
                        //库存表
                        DownloadStoreNumTask product4 = new DownloadStoreNumTask(2);
                        product4.executeOnExecutor(Executors.newCachedThreadPool());
                    } else if (file.getName().equals("tbl_productorder.csv")) {
                        //订单表
                       /* DownloadOrderTask product = new DownloadOrderTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());*/
                    } else if (file.getName().equals("tbl_brandkeywords.csv")) {
                        //品牌表
                        DownloadKeyWordsTask product = new DownloadKeyWordsTask();
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    }
                }
            }

            loadData(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ApkUpdateTask extends TimerTask {

        private ApkUpdateTask() {

        }

        public void run() {
            if (Utils.isNetworkConnected(App.mContext)) {
                //库存更新
                if(!App.isStoreNumUpdating){
                    UpdateStoreNumTask product1 = new UpdateStoreNumTask();
                    product1.executeOnExecutor(Executors.newCachedThreadPool());
                }
                //订单更新
                if (!App.isOrderUpdating) {
                    UpdateOrderTask product2 = new UpdateOrderTask();
                    product2.executeOnExecutor(Executors.newCachedThreadPool());
                }
                if(!App.isEmpBrandUpdating){
                    UpdateEmpBrandTask product3 = new UpdateEmpBrandTask();
                    product3.executeOnExecutor(Executors.newCachedThreadPool());
                }
                if(!App.isEmpStorehouseUpdating) {
                    UpdateEmpStorehouseTask product4 = new UpdateEmpStorehouseTask();
                    product4.executeOnExecutor(Executors.newCachedThreadPool());
                }
                if(!App.isShopsUpdating) {
                    //商品更新
                    UpdateShopsTask product5 = new UpdateShopsTask();
                    product5.executeOnExecutor(Executors.newCachedThreadPool());
                }
                /*if(!App.isProductTypeUpdating) {
                    //商品类别更新
                    UpdateProductTypeTask product6 = new UpdateProductTypeTask();
                    product6.executeOnExecutor(Executors.newCachedThreadPool());
                }*/
                if(!App.isBrandKeywordUpdating) {
                    //商品分类更新
                    UpdateBrandKeywordTask product7 = new UpdateBrandKeywordTask();
                    product7.executeOnExecutor(Executors.newCachedThreadPool());
                }
                //应用更新检测
                if (!BuildConfig.DEBUG && App.mIsUpdate) {
                    DownloadUpdateFileTask product12 = new DownloadUpdateFileTask(MainActivity.this, 1);
                    product12.executeOnExecutor(Executors.newCachedThreadPool());
                }
                if(!App.isPriceTypeUpdating) {
                    //价格套更新
                    UpdatePriceTypeTask product8 = new UpdatePriceTypeTask();
                    product8.executeOnExecutor(Executors.newCachedThreadPool());
                }

                if(!App.isProductPriceUpdating) {
                    //商品价格表更新
                    UpdateProductPriceTask product9 = new UpdateProductPriceTask();
                    product9.executeOnExecutor(Executors.newCachedThreadPool());
                }

                if(!App.isStoreHouseUpdating) {
                    //仓库表更新
                    UpdateStoreHouseTask product10 = new UpdateStoreHouseTask();
                    product10.executeOnExecutor(Executors.newCachedThreadPool());
                }

                if(!App.isClientPriceUpdating) {
                    //商店与价格套关系表更新
                    UpdateClientPriceTask product11 = new UpdateClientPriceTask();
                    product11.executeOnExecutor(Executors.newCachedThreadPool());
                }

                if (!App.isCustomerUpdating) {
                    //商店更新
                    UpdateCustomerTask product12 = new UpdateCustomerTask();
                    product12.executeOnExecutor(Executors.newCachedThreadPool());
                }
                if (!App.isCustomerStoreUpdating) {
                    //门店更新
                    UpdateCustomerStoreTask product13 = new UpdateCustomerStoreTask();
                    product13.executeOnExecutor(Executors.newCachedThreadPool());
                }
                if (!App.isSaleCustomerUpdating) {
                    //商店关联更新
                    UpdateSaleCustomerTask product14 = new UpdateSaleCustomerTask();
                    product14.executeOnExecutor(Executors.newCachedThreadPool());
                }
                if (!App.isSaleCustomerStoreUpdating) {
                    //门店关联更新
                    UpdateSaleCustomerStoreTask product15 = new UpdateSaleCustomerStoreTask();
                    product15.executeOnExecutor(Executors.newCachedThreadPool());
                }
               /* if (!App.isProductBrandUpdating) {
                    //品牌更新
                    UpdateProductBrandTask product16 = new UpdateProductBrandTask();
                    product16.executeOnExecutor(Executors.newCachedThreadPool());
                }*/
            }
        }
    }

    public static class UpdateHouseTask extends TimerTask {
        private static UpdateHouseTask instance;

        private UpdateHouseTask() {

        }

        public static UpdateHouseTask getInstance() {
            if (instance == null) {
                instance = new UpdateHouseTask();
            }
            return instance;
        }

        public void run() {
            if (Utils.isNetworkConnected(App.mContext) && !App.isOrderUpdating) {
                UpdateOrderTask product7 = new UpdateOrderTask();
                product7.executeOnExecutor(Executors.newCachedThreadPool());
                //sendOrder();
            }
        }

        private void sendOrder() {
            try {
                String url = NetUtils.INSERT_ORDER;
                SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
                // 创建请求参数的封装的对象
                client.setTimeout(30000);
                // 创建请求参数的封装的对象
                JSONObject jsonObject = new JSONObject();
                //jsonObject.put("userId", SharedPreference.getPreferString("id"));
                jsonObject.put("dealerId", "xgx");
                jsonObject.put("orderSource", 2);
                jsonObject.put("phoneNum", "");
                jsonObject.put("versionName", "1.0");
                jsonObject.put("custmerId", "1101001");
                jsonObject.put("custmerName", "赤坎百汇购物超市(收现款)");
                jsonObject.put("houseId", "");
                jsonObject.put("houseName", "");
                jsonObject.put("businessId", "111");
                jsonObject.put("businessName", "湛江宝洁经营部");
                jsonObject.put("employerId", "1002");
                jsonObject.put("employerName", "陈云飞");
                jsonObject.put("orderTotalPrice", "895.5");
                //jsonObject.put("orderTotalPrice", 0.01);
                jsonObject.put("payType", 1);
                jsonObject.put("deliveryType", 1);
                jsonObject.put("orderStatus", "SUBM");
                jsonObject.put("dstAddr", "湛江赤坎区金城一横路21号（即沿江华庭入口旁)");
                jsonObject.put("telephone", "2222222222");
                jsonObject.put("communicatePeople", "赤坎百汇购物超市(收现款)");
                jsonObject.put("orderDetailList", Utils.getJSONArray(getList()));
                Log.d(TAG, "order " + url);
                Log.d(TAG, "order " + jsonObject.toString());
                ByteArrayEntity stringEntity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
                stringEntity.setContentType("application/json");
                //StringEntity stringEntity = new StringEntity(jsonObject.toString());
                // 执行post方法
                client.post(mContext, url, stringEntity, "application/json", new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
                        Log.d(TAG, "order " + responseBody.toString());
                        try {
                            if (responseBody.getInt("status") == 200) {
                            } else {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        throwable.printStackTrace();// 把错误信息打印出轨迹来
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static List<SendOrderDetail> getList() {
        List<SendOrderDetail> detaillist = new ArrayList<>();
        detaillist.clear();
        for (int position = 0; position < 2; position++) {
            SendOrderDetail orderDetail = new SendOrderDetail();
            orderDetail.setProductInfoId("82209805");
            orderDetail.setProductBarCode("6903148080948");
            orderDetail.setStoreHouseId("121");
            orderDetail.setStoreHouseName("广东宝洁中心仓");
            orderDetail.setProductInfoName("OLAY美白滋养沐浴香皂125G");
            orderDetail.setCalcParam("72");
            orderDetail.setSmallUnitCount("1");
            orderDetail.setLargeUnitCount("1");
            orderDetail.setUnitSalePrice("5.97" + "");
            orderDetail.setProductSalePrice("435.81");
            orderDetail.setLast_discount("101.4062257817");
            orderDetail.setOrderSource(2);
            orderDetail.setUcti(5.97);
            orderDetail.setUcte(5.1025641026);
            orderDetail.setSalePriceT4(5.97);
            orderDetail.setRealUcti(5.97);
            orderDetail.setRealUcte(5.97);
            orderDetail.setTcti(435.81);
            orderDetail.setTcte(372.4871794898);
            orderDetail.setDiscountRate(100.0);
            orderDetail.setTaxRate(17);
            orderDetail.setTaxAmount(435.81 - 372.4871794898);
            orderDetail.setInitPrice(5.97);
            detaillist.add(orderDetail);
        }
        return detaillist;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        DBHelper.getInstance().close();
        startLocation.stotLocation();
        AppManager.getAppManager().removeActivity(this);
        UpdateHouseTask.getInstance().cancel();
        new ApkUpdateTask().cancel();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.re_home_shop:
                mCurrentPage = 1;
                showShop();
                break;
            case R.id.re_home_order:
                mCurrentPage = 2;
                showOrder();
                break;
            case R.id.re_home_task:
                mCurrentPage = 3;
                showTask();
                break;
            case R.id.re_home_my:
                mCurrentPage = 4;
                showMy();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        int id = getIntent().getIntExtra("id", 0);
        Log.d(TAG, "onResume " + "id:" + id);
        if (id == 1) {
            showShop();
        } else if (id == 2) {
            showOrder();
        } else if (id == 3) {
            showTask();
        } else if (id == 4) {
            showMy();
        }
        getIntent().removeExtra("id");
    }

    private void showTask() {
        ib_home_shop.setImageResource(R.drawable.tab_infomation);
        tv_home_shop.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_order.setImageResource(R.drawable.tab_schedule);
        tv_home_order.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_task.setImageResource(R.drawable.tab_service_clk);
        tv_home_task.setTextColor(getResources().getColor(R.color.title));

        ib_home_my.setImageResource(R.drawable.tab_contacts);
        tv_home_my.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        showFragment("Task");

    }

    private void showMy() {
        ib_home_shop.setImageResource(R.drawable.tab_infomation);
        tv_home_shop.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_order.setImageResource(R.drawable.tab_schedule);
        tv_home_order.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_task.setImageResource(R.drawable.tab_service);
        tv_home_task.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_my.setImageResource(R.drawable.tab_contacts_clk);
        tv_home_my.setTextColor(getResources().getColor(R.color.title));

        showFragment("My");
    }

    private void showShop() {
        ib_home_shop.setImageResource(R.drawable.tab_infomation_clk);
        tv_home_shop.setTextColor(getResources().getColor(R.color.title));

        ib_home_order.setImageResource(R.drawable.tab_schedule);
        tv_home_order.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_task.setImageResource(R.drawable.tab_service);
        tv_home_task.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_my.setImageResource(R.drawable.tab_contacts);
        tv_home_my.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        showFragment("Shop");
    }

    private void showOrder() {
        ib_home_shop.setImageResource(R.drawable.tab_infomation);
        tv_home_shop.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_order.setImageResource(R.drawable.tab_schedule_clk);
        tv_home_order.setTextColor(getResources().getColor(R.color.title));

        ib_home_task.setImageResource(R.drawable.tab_service);
        tv_home_task.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_my.setImageResource(R.drawable.tab_contacts);
        tv_home_my.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        showFragment("Order");
    }

    private void showFragment(String paramString) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragments(fragmentTransaction);
        switch (paramString) {
            case "Shop":
                // 如果fg1为空，则创建一个并添加到界面上

                if (mShopFragment == null) {
                    Log.d(TAG, "mShopFragment == null");
                    mShopFragment = new ShopFragment();
                    fragmentTransaction.add(R.id.fragment_container, mShopFragment);
                } else {
                    Log.d(TAG, "mShopFragment != null");
                    // 如果不为空，则直接将它显示出来
                    fragmentTransaction.show(mShopFragment);
                }
                break;
            case "Order":
                // 如果fg2为空，则创建一个并添加到界面上
                if (mOrderFragment == null) {
                    mOrderFragment = new OrderFragment();
                    fragmentTransaction.add(R.id.fragment_container, mOrderFragment);
                } else {
                    // 如果不为空，则直接将它显示出来
                    fragmentTransaction.show(mOrderFragment);
                }
                break;

            case "Task":
                // 如果fg2为空，则创建一个并添加到界面上
                if (mMallFragment == null) {
                    mMallFragment = new MallFragment();
                    fragmentTransaction.add(R.id.fragment_container, mMallFragment);
                } else {
                    // 如果不为空，则直接将它显示出来
                    fragmentTransaction.show(mMallFragment);
                }
                break;

            case "My":
                // 如果fg4为空，则创建一个并添加到界面上
                if (mUserFragment == null) {
                    mUserFragment = new UserFragment();
                    fragmentTransaction.add(R.id.fragment_container, mUserFragment);
                } else {
                    // 如果不为空，则直接将它显示出来
                    fragmentTransaction.show(mUserFragment);
                }
                break;
        }
        fragmentTransaction.commit(); // 提交
    }

    /**
     * 隐藏Fragment
     */
    private void hideFragments(FragmentTransaction fragmentTransaction) {
        if (mShopFragment != null) {
            fragmentTransaction.hide(mShopFragment);
        }
        if (mOrderFragment != null) {
            fragmentTransaction.hide(mOrderFragment);
        }
        if (mMallFragment != null) {
            fragmentTransaction.hide(mMallFragment);
        }
        if (mUserFragment != null) {
            fragmentTransaction.hide(mUserFragment);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次返回将退出应用", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            AppManager.getAppManager().finishAllActivity();
            System.exit(0);
        }
    }
}
